var timerID;

$(function() {
	$('.peMopho').mouseover(function(){
			var preview = $(this);
			var url = preview.attr('data-preview');
			var bg_image = new Image();
			var bg_height;
			var bg_width;
			var frame_height = preview.height();
			var frame_width = preview.width();
			var bgWidthPos = 0;
			var bgHeightPos = 0;
			
			var framesNum = 6297;
			var framesCount = 0;
			
			bg_image.src = url;
			bg_image.onload = function() {
				bg_height = this.height;
				bg_width = this.width;
				preview.css('background-image', 'url(' + url + ')');
				
				clearInterval(timerID);
				preview.find('img').css('opacity', 0);
				/*timerID = setInterval(function () {
					if (bgHeightPos + frame_height >= bg_height)
						bgHeightPos = 0;
					else
						bgHeightPos += frame_height;
					preview.css('background-position', '0px ' + bgHeightPos + 'px');
				}, 40);*/
				
				timerID = setInterval(function () {
					framesCount++;
					
					if (framesCount <= framesNum)
					{
						if (bgWidthPos + frame_width >= bg_width)
						{
							bgWidthPos = 0;
							if (bgHeightPos + frame_height >= bg_height)
								bgHeightPos = 0;
							else
								bgHeightPos += frame_height;
						}
						else
							bgWidthPos += frame_width;
						preview.css('background-position', '-' + bgWidthPos + 'px ' + '-' + bgHeightPos + 'px');
					}
					else
					{
						bgWidthPos = 0;
						bgHeightPos = 0;
					}
				}, 40);
				
				preview.data('timerID', timerID); 
			};
		}).mouseout(function backgroundMoveStop()
		{
			clearInterval(timerID);
			$(this).find('img').css('opacity', 1);
		}
	);
});